package com.longrise.android.byjk.plugins.aboutme.personalInfo.product_show;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.common.base.BaseActivity;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.plugins.aboutme.personalInfo.request.BaseRequestResult;
import com.longrise.android.byjk.plugins.aboutme.personalInfo.request.PersionRequest;
import com.longrise.common.utils.NetUtil;
import com.longrise.android.byjk.widget.view.BaseFrameView;

/**
 * Created by callxkj on 2016/11/21.
 * 产品展示
 */

public class ProductShowActivity extends BaseActivity implements View.OnClickListener, BaseFrameView.ReloadListener {

    private static final String TAG = "ProductShowActivity";

    private final String SAVEINSTANCE_IS_REFUSH = "SAVE_IS_REFUSH";

    private final int MSG_ON_START = 0;
    private final int MSG_ON_ERROR = 1;
    private final int mSG_ON_FINISH = 2;

    private Toolbar mTitle;


    private LinearLayout mLinearProductShow;
    private LinearLayout mLinearAddProduct;
    private Button mBtnAdd;
    private Button mBtnContinueAdd;

    private ProductAdapter mProductAdapter = null;
    private ListView mListView;
    private BaseFrameView mBaseFrameView = null;

    private boolean mIsRefrushPersonalInfor = false;  //确认是否添加新的保险方案
    private boolean mDestory;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mDestory) return;
            switch (msg.what) {
                case MSG_ON_START:
                    try {
                        mLinearProductShow.setVisibility(View.GONE);
                        mLinearAddProduct.setVisibility(View.GONE);
                        mBaseFrameView.setVisibility(View.VISIBLE);
                        mBaseFrameView.setLoadingStatus(BaseFrameView.LoadingStatus.LOADING);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;

                case MSG_ON_ERROR:
                    try {
                        mLinearProductShow.setVisibility(View.GONE);
                        mLinearAddProduct.setVisibility(View.GONE);
                        mBaseFrameView.setVisibility(View.VISIBLE);
                        mBaseFrameView.setLoadingStatus(BaseFrameView.LoadingStatus.ERROR);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;

                case mSG_ON_FINISH:
                    try {
                        mBaseFrameView.setVisibility(View.GONE);
                        mBaseFrameView.setLoadingStatus(BaseFrameView.LoadingStatus.SUCCESS);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;

                default:
                    break;
            }
        }
    };

    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            mIsRefrushPersonalInfor = savedInstanceState.getBoolean(SAVEINSTANCE_IS_REFUSH);
        }
        return R.layout.activity_productshow;
    }


    @Override
    public void initView() {
        mLinearProductShow = (LinearLayout) findViewById(R.id.linearlayout_productshow);
        mLinearAddProduct = (LinearLayout) findViewById(R.id.linearlayout_add_product);
        mBtnAdd = (Button) findViewById(R.id.productshow_bt_add);
        mBtnContinueAdd = (Button) findViewById(R.id.productshow_continue_add);
        mListView = (ListView) findViewById(R.id.products_listview);
        mBaseFrameView = (BaseFrameView) findViewById(R.id.product_bf);

        initTitle();
        initEvent();

        if (checkNetwork()) {
            mHandler.sendEmptyMessage(MSG_ON_START);
            requestProduct();
        }

    }

    private void initEvent() {
        mBtnContinueAdd.setOnClickListener(this);
        mBtnAdd.setOnClickListener(this);
        mBaseFrameView.setOnReloadListener(this);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    EntityBean entityBean = (EntityBean) mProductAdapter.getItem(position);
                    Intent intent = new Intent(ProductShowActivity.this, AddProductShowActivity.class);
                    intent.putExtra("productid", entityBean.getString("productid"));
                    intent.putExtra("productname", entityBean.getString("productname"));
                    intent.putExtra("productdesc", entityBean.getString("productdesc"));
                    openAddProduct(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void initTitle() {
        mTitle = (Toolbar) findViewById(R.id.byjk_toolbar);
        mTitle.setTitle(getString(R.string.cpzs));
        setSupportActionBar(mTitle);
        mTitle.setNavigationOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                close();
            }
        });
    }

    private void requestProduct() {
        EntityBean bean = new EntityBean();
        bean.set("userid", UserInfor.getInstance().getUserid());
        bean.set("cardno", UserInfor.getInstance().getUsersfzh());
        EntityBean reqBean = new EntityBean();
        reqBean.set("bean", bean);
        commitRequest(reqBean, "bbt_user_sInsuranceProduct");
    }

    private void commitRequest(EntityBean re, String url) {
        PersionRequest persionRequest = new PersionRequest(new ProductResult());
        persionRequest.request(this, url, re);
    }

    @Override
    public void onReload(View v) {
        if (checkNetwork()) {
            requestProduct();
        }
    }

    private class ProductResult extends BaseRequestResult {

        @Override
        public void onSuccess(EntityBean bean) {
            if (bean != null) {
                int resultstate = bean.getInt("resultstate");
                if (resultstate == 0) {
                    showToast(bean.getString("resultdesc"));
                    setVisible(View.GONE, View.GONE);
                    mHandler.sendEmptyMessage(MSG_ON_ERROR);
                } else if (resultstate == 1) {
                    mHandler.sendEmptyMessage(mSG_ON_FINISH);
                    setVisible(View.GONE, View.VISIBLE);
                    setProductAdapter(bean.getBeans("result"));
                } else if (resultstate == 2) {
//                    showToast(bean.getString("resultdesc"));
                    mHandler.sendEmptyMessage(mSG_ON_FINISH);
                    setVisible(View.VISIBLE, View.GONE);
                }
            }
        }

        @Override
        public void onFailure(String error) {
            //错误处理
            mHandler.sendEmptyMessage(MSG_ON_ERROR);
            showToast(getString(R.string.nonetwork));
        }

        @Override
        public void onFinish() {
        }
    }

    private void setVisible(int addproduct, int productshow) {
        mLinearAddProduct.setVisibility(addproduct);
        mLinearProductShow.setVisibility(productshow);
    }

    private void setProductAdapter(EntityBean[] been) {
        if (mProductAdapter == null) {
            mProductAdapter = new ProductAdapter(this);
            mProductAdapter.setData(been);
            mListView.setAdapter(mProductAdapter);
        } else {
            mProductAdapter.setData(been);
            mProductAdapter.notifyDataSetChanged();
        }
        if (been != null && been.length >= 3) {
            mBtnContinueAdd.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.productshow_bt_add:
                openAddProduct(new Intent(this, AddProductShowActivity.class));
                break;

            case R.id.productshow_continue_add:
                openAddProduct(new Intent(this, AddProductShowActivity.class));
                break;
        }
    }

    private boolean checkNetwork() {
        if (!NetUtil.checkNetEnable()) {
            mHandler.sendEmptyMessage(MSG_ON_ERROR);
            return false;
        } else {
            return true;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            boolean isAddSuccess = data.getBooleanExtra("key", false);
            if (isAddSuccess && checkNetwork()) {
                mHandler.sendEmptyMessage(MSG_ON_START);
                requestProduct();
                mIsRefrushPersonalInfor = true;
            }
        }
    }

    private void close() {
        setResult(-10, new Intent().putExtra("key", mIsRefrushPersonalInfor));
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            close();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void openAddProduct(Intent intent) {
        startActivityForResult(intent, 10);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(SAVEINSTANCE_IS_REFUSH, mIsRefrushPersonalInfor);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mDestory = true;
    }
}
